package com.sparrow.source.common.utils;

import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

/**
 * @author bryceyung
 * @since 2024/11/21
 */
@Component
public class ImageUtils {

    /**
     * 图片转base64
     *
     * @param imagePath
     * @return
     * @throws IOException
     */
    public String imageToBase64(String imagePath) throws IOException {
        Path path = new File(imagePath).toPath();
        byte[] imageBytes = Files.readAllBytes(path);
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    /**
     * 读取远程文件Base64编码
     *
     * @param remoteImagePath
     * @return
     * @throws Exception
     */
    public String remoteImageToBase64(String remoteImagePath) throws IOException {
        URL url = new URL(remoteImagePath);
        URLConnection connection = url.openConnection();

        try (BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            return Base64.getEncoder().encodeToString(baos.toByteArray());
        }
    }

}
